<?php

/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/9/13
 * Time: 4:02 PM
 * To change this template use File | Settings | File Templates.
 */
class SiteController extends Controller {
    public function accessRules() {
        return array();
    }

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function actions() {
        return array();
    }

    public function  actionIndex() {
        $detect = new Mobile_Detect;
        if ($detect->isMobile()) {
            $this->layout = '//layouts/main_mobile';
            $this->render('index');
        } else {
            $this->layout = '//layouts/main_map';
            $this->render('map', array('zip_code' => 0));
        }

    }

    public function  actionMap() {
        $this->layout = '//layouts/main_map';
        session_regenerate_id();
        $banned = HSCommon::checkBanned();
        if ($banned) {
            $this->redirect(HSUrl::getUnbanUrl());
        }
        $zip = isset($_GET['zipcode']) ? trim($_GET['zipcode']) : 0;
        $this->render('map', array('zip_code' => $zip));
    }

    #region CODE

    public function actionAddDB() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/src.txt';
        $arr = array_filter(explode('|', file_get_contents($src)));
        foreach ($arr as $item) {
            $values = HSCommon::handleArray(array_filter(explode(';', $item)));
            if (count($values) >= 6) {
                $company = new Company();
                $company->category_vn = trim($values[0]);
                $company->category_en = trim($values[1]);
                $company->name = trim($values[2]) == 'KO' ? '' : trim($values[2]);
                $company->owner = trim($values[3]) == 'KO' ? '' : trim($values[3]);
                $company->address = trim($values[4]);
                $company->city = trim($values[5]);
                $company->phone = trim($values[6]) == 'KO' ? '' : trim($values[6]);

                $company->save();
            }
        }
    }

    public function  actionAddCat() {
        $coms = Company::model()->findAll();
        foreach ($coms as $com) {
            $old_cat = Category::model()->findByAttributes(array('name_vn' => $com->category_vn));
            if ($old_cat != null) {
                $com->category_id = $old_cat->id;
                if (!$com->save()) {
                    var_dump($com);
                    var_dump($com->getErrors());
                    echo "a";
                    die;
                }
            } else {
                $cat = new Category();
                $cat->name_vn = $com->category_vn;
                $cat->name_en = $com->category_en;
                if ($cat->save()) {
                    $com->category_id = $cat->id;
                    $com->save();
                } else {
                    var_dump($cat->getErrors());
                    die;
                }
            }

        }
    }

    public function actionMigrate() {
        $coms = Company::model()->findAll();
        foreach ($coms as $com) {
            $com->name = $com->name == 'KO' ? '' : $com->name;
            $com->owner = $com->owner == 'KO' ? '' : $com->owner;
            $com->address = $com->address == 'KO' ? '' : $com->address;
            $com->phone = $com->phone == 'KO' ? '' : $com->phone;
            $com->city = $com->city == 'KO' ? '' : $com->city;
            if (!$com->save()) {
                var_dump($com->getErrors());
                die;
            }
        }
    }

    public function actionGetCoordinates() {

        $coms = Company::model()->findAll(array(
            'select' => '*',
            'condition' => 'lng= "" and address != ""',
            'limit' => 1000
        ));
        foreach ($coms as $com) {
            $address = "$com->address $com->city";
            $address = str_replace(' ', '+', $address);
            $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=' . Yii::app()->params['API_key'];

            if (!$response = file_get_contents($url))
                exit('Could not get response');

            $response = json_decode($response);
            if ($response->status == 'ZERO_RESULTS')
                continue;

            $latitude = $response->results[0]->geometry->location->lat;
            $longitude = $response->results[0]->geometry->location->lng;
            $com->lng = $longitude;
            $com->lat = $latitude;
            $com->published = 1;
            if (!$com->save()) {
                var_dump($com->getErrors());

                die;
            }

        }

//        $this->render('get_coordinates');
    }

    public function actionTest() {
//        $lat = 10.763090799999999;
//        $lng = 106.6573169;
//        $url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&key=' . Yii::app()->params['API_key'];
//        if (!$response = file_get_contents($url))
//            exit('Could not get response');
//        $response = json_decode($response);
//        var_dump($response->results[0]->formatted_address);
//        die;
//        var_dump($response['results']['formatted_address']);

        for ($i = 0; $i < 10; $i++) {
            $comment = new Comment();
            $comment->content = 'Không có tiền thưởng tết buồn quá!!! Không có tiền thưởng tết buồn quá!!! Không có tiền thưởng tết buồn quá!!! Không có tiền thưởng tết buồn quá!!! Không có tiền thưởng tết buồn quá!!! Không có tiền thưởng tết buồn quá!!! ';
            $comment->email = 'nvhuusang@gmail.com';
            $comment->username = 'nguyen huu sang';

            $comment->created_time = time();
            $comment->company_id = 3290;
            $comment->published = 1;
            $comment->parent_id = 0;
            $comment->like_count = 0;
            $comment->save();

        }
    }

    public function actionAddData() {

        $src = dirname(Yii::getPathOfAlias('application')) . '/src.txt';
        $arr = array_filter(explode('|', file_get_contents($src)));
        if (count($arr) != 3289) {
            var_dump('error');
            die;
        }
        foreach ($arr as $k => $item) {
            if (trim($item) == '') continue;
            $id = $k + 1;
            $company = new Company();
            $company = Company::model()->findByPk($id);
            if ($company == null) {
                var_dump($k);
                var_dump($id);
                die;
            }
            $company->phone = trim($item);

            $company->save();
        }
    }

    public function actionMigrateZipcode() {
        $companies = Company::model()->findAll();
        foreach ($companies as $company) {
            preg_match('!\d+!', $company->city, $match);
            if (count($match) > 0) {
                $company->zipcode = trim($match[0]);
                $company->save();
            }
        }
    }

    public function actionAddCompare() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/src.txt';
        $arr = array_filter(explode(';', file_get_contents($src)));
        $arr = array_unique($arr);
        foreach ($arr as $item) {
            $value = trim($item);
            $old = Compare::model()->findByAttributes(array('value' => $value, 'type' => CompareTypeEnum::zip));
            if ($old != null) continue;

            $compare = new Compare();
            $compare->type = CompareTypeEnum::zip;
            $compare->value = $value;
            $compare->save();

        }
    }

    public function actionFixName() {
        $companies = Company::model()->findAll();
        foreach ($companies as $company) {
            $company->name = HSCommon::removeMultipleBlank($company->name);
            $company->save();
        }

    }

    #endregion

    public function actionUnban() {
        $model = new BanForm();
        $private = "6LdiDPISAAAAAAKunlYLWMcCykD4wShGMSTJqnAc";
        require_once('recaptchalib.php');
        if (isset($_POST['recaptcha_challenge_field'])) {

            $chanllenge = isset($_POST["recaptcha_challenge_field"]) ? $_POST["recaptcha_challenge_field"] : "";
            $response = isset($_POST["recaptcha_response_field"]) ? $_POST["recaptcha_response_field"] : "";
            $resp = recaptcha_check_answer($private, $_SERVER["REMOTE_ADDR"], $chanllenge, $response);
            if (!$resp->is_valid) {
                $model->addError('captcha', "Anti Spam nhập không chính xác. Vui lòng nhập lại");
            } else {
                $ip = HSCommon::getUserIp();
                $ban = BannedIps::model()->findByAttributes(array('ip' => $ip));
                SessionsPerIp::model()->deleteAllByAttributes(array('ip' => $ip));
                if ($ban != null) {
                    $ban->delete();
                }
                $this->redirect(HSUrl::home());
            }
        }

        $this->render('unban', array('model' => $model));
    }

    public function actionError() { $this->redirect(HSUrl::home()); }

    public function actionContact() {
        $this->render('contact');
    }

    public function actionDelete() {
        $companies = Company::model()->deleteAll(array(
            'select' => '*',
            'condition' => 'address = ""'
        ));

        $companies = Company::model()->deleteAll(array(
            'select' => '*',
            'condition' => 'name = "" and owner = ""'
        ));

//        $html = '<h2>Những công ty không có đia chỉ</h2>';
//        $html = '<table><tr><th>Danh mục VN</th><th>Danh mục EN</th> <th>Tên</th><th>Tên người sở hữu</th><th>Địa chỉ</th><th>Thành phố, tiểu bang ,zipcode</th><th>Phone</th></tr>';
//        foreach ($companies as $company) {
//            $html .= "<tr>";
//            $html .= "<td>$company->category_vn</td>";
//            $html .= "<td>$company->category_en</td>";
//            $html .= "<td>$company->name</td>";
//            $html .= "<td>$company->owner</td>";
//            $html .= "<td>$company->address</td>";
//            $html .= "<td>$company->city</td>";
//            $html .= "<td>$company->phone</td>";
//            $html .= "</tr>";
//
//        }
//
//        $this->render('contact', array('html' => $html));
//        Mailer::sendEmail('pro201@gmail.com', 'Những dòng cần xóa trong niên giám', $html);
    }

    public function actionExportCategories() {
        $categories = AdCategory::model()->findAll();

        foreach ($categories as $cat) {
            echo "<item>$cat->name</item>";
        }
        $this->render('index');
    }

    public function actionAddAdCategories() {
        $str = "Bán Các Loại;Bảng Hiệu;Cần Thuê Nhà/Phòng;Cơm Tháng;Dạy/Huấn Luyện;Dịch Vụ;Dọn Nhà;Du Lịch;Giặt Thảm;Giữ Trẻ;Khuyến mãi/Coupon;Làm Vườn;Nhà Bán;Nhà Cho Thuê;Nhắn Tin/Thông Báo;Phòng Cho Thuê;Sang Nhượng Cơ Sở;Sửa Máy Móc;Sửa Nhà/Tiệm;Sửa Ống Nước;Sửa Xe;Sức Khỏe/Thẩm Mỹ;Tìm Bạn Bốn Phương;Tìm Người Thân/Quen;Tử Vi/Chiêm Tinh;Việc Chợ/Nhà Hàng;Việc Hair/Nail;Việc Hãng Xưởng;Linh tinh";

        $arr = array_filter(explode(";", $str));
        foreach ($arr as $i) {
            $cat = new AdCategory();
            $cat->name = trim($i);
            $cat->save();
        }

    }

}